package com.chaofan.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.lang.Nullable;

import java.text.SimpleDateFormat;

public class JsonUtil {
    public static String toJson(Object obj, @Nullable String format) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        if (format != null) {
            mapper.setDateFormat(new SimpleDateFormat(format));
        }
        return mapper.writeValueAsString(obj);
    }

    public static String toJson(Object obj) throws JsonProcessingException {
        return toJson(obj, null);
    }
}
